<template>
  <div class="form-view-css">
    <el-dialog :visible.sync="visible"
               :show-close="true"
               ref="dialog"
               :append-to-body="true"
               :close-on-click-modal="false"
               :modal="true"
               :close-on-press-escape="false"
               :destroy-on-close="true"
               :width="width?width:'55%'"
               @close="resetFormMaking">
      <!-- :before-close="resetFormMaking" -->
      <div v-loading="loading"
           v-if="jsonData.list">
        <fm-generate-form :data="jsonData"
                          :remote="remoteFuncs"
                          :remoteOption="remoteOption"
                          ref="generateForm">
        </fm-generate-form>
      </div>
      <span slot="footer"
            class="form-dialog-footer">
        <el-button size="mini"
                   @click="resetFormMaking">{{$t('cancel')}}</el-button>
        <el-button size="mini"
                   type="primary"
                   :disabled="formViewData.dataFrom&&formViewData.dataFrom==='review'"
                   @click="addOrUpdateFormData">{{formViewData.isNew ? $t('add') : $t('confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import Cookies from 'js-cookie'
import getDataset from './form-fuction'
import http from '@/utils/request'
import debounce from 'lodash/debounce'
import moment from 'moment'
export default {
  props: {
    formViewData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rowDataItem: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      loading: false,
      visible: false,
      jsonData: {},
      dynamicData: {
        radio_options: []
      },
      remoteFuncs: {
        func_options (resolve) {
          getDataset.clientList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        },
        clientList (resolve) {
          getDataset.timeZoneList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        }
      },
      width: '',
      remoteOption: {}

    }
  },
  watch: {
    visible: {
      handler: function (val) {
        if (val) {
          // this.id = this.formViewData.id
          this.getJsonData()
        }
      },
      immediate: true,
      deep: true
    }

  },
  methods: {
    init () {
      this.$nextTick(() => {
        //    if (this.$refs['generateForm']) this.$refs['generateForm'].reset()
        if (this.formViewData.formCode) {
          this.getJsonData()
        }
      })
      this.visible = true
    },
    resetFormMaking () {
      this.jsonData = {}
      if (this.$refs.generateForm) {
        // this.$refs.generateForm.reset()
      }
      Object.assign(this.$data, this.$options.data())
      this.visible = false
    },
    getJsonData () {
      var _self = this
      let formCode = _self.formViewData.formCode
      const params = { formCode: formCode }
      // _self.loading = true
      this.$interface.reports.getjsonDataApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        var temp = _self.apiConfig(res.data.formSchema)
        _self.jsonData = temp
        _self.$nextTick(() => {
          _self.$refs.generateForm.refresh()
        })
        _self.formVersion = res.data.formVersion
        if (_self.formViewData.action === 'rowdataview') {
          _self.$nextTick(() => {
            if (_self.rowDataItem.material_list && typeof _self.rowDataItem.material_list ==='string') { _self.rowDataItem.material_list = JSON.parse(_self.rowDataItem.material_list) }
            if (_self.rowDataItem.oppo_list && typeof _self.rowDataItem.oppo_list ==='string') { _self.rowDataItem.oppo_list = JSON.parse(_self.rowDataItem.oppo_list) }
            if (_self.$refs['generateForm']) { _self.$refs['generateForm'].setData(_self.rowDataItem) }
          })
        } else if (_self.formViewData.dataFrom === 'rowdata') {
          _self.$nextTick(() => {
            if (_self.rowDataItem.material_list && typeof _self.rowDataItem.material_list ==='string') { _self.rowDataItem.material_list = JSON.parse(_self.rowDataItem.material_list) }
            if (_self.rowDataItem.oppo_list && typeof _self.rowDataItem.oppo_list ==='string') { _self.rowDataItem.oppo_list = JSON.parse(_self.rowDataItem.oppo_list) }
            if (_self.$refs['generateForm']) { _self.$refs['generateForm'].setData(_self.rowDataItem) }
          })
        } else {
          const params = { id: this.rowDataItem[this.formViewData.formKey] }
          this.$interface.reports.getFormDataApi(params).then(({ data: res }) => {
            if (res.code !== 0) {
              this.$emit('closeLoading')
              return this.$message.error(res.msg)
            }
            this.formVersion = res.data.form.formVersion
            this.$nextTick(() => {
              this.$refs.generateForm.setData(res.data.data.dataContent)
            })
          }).catch(() => {

          })
        }
      }).catch(() => {

      })

      if (_self.formViewData.dataFrom === 'api') {

      }
      _self.$forceUpdate()
      //
    },
    apiConfig (res) {
      if (res.config.dataSource) {
        res.config.dataSource.forEach(item => {
          if (!item.url.startsWith('http')) item.url = http.options.baseURL + item.url
          item.headers.tenantCode = Cookies.get('tenant_code') || ''
          item.headers.timezoneOffset = store.state.user.timezoneOffset ? store.state.user.timezoneOffset : ''
          item.headers.token = Cookies.get('token') || ''
        })
      }
      return res
    },
    JsondataFormat (data) {
      let temp = null
      temp = data
      if (temp['ticket_status_key']) {
        let item = this.jsonData.list.find(e => e.model === 'ticket_status_key').options.options
        if (item && Array.isArray(item) && item.length > 0) {
          let findIndex = item.findIndex(item => {
            return (item.value).toString() === (temp['ticket_status_key']).toString()
          })
          if (item[findIndex + 1] && item[findIndex + 1].value) temp['ticket_status_key'] = item[findIndex + 1].value
        }
      }
      if(this.formViewData.actionConfig&&this.formViewData.actionConfig.type === 'addKey'){
        let tempData = this.execObject(this.formViewData.actionConfig.params,data)
        temp = this._.merge(temp,tempData)
      }
      return temp
    },
    addOrUpdateFormData: debounce(function () {
      this.$refs.generateForm.getData().then((val) => {
        if (this.formViewData&&this.formViewData.actionConfig&&this.formViewData.actionConfig.type === 'apiConfig') {
          this.apiRequest(this.formViewData.actionConfig,this.JsondataFormat(val))
        } else {
          this.formSubmit(val)
        }
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    formSubmit (val) {
      let formCode = this.formViewData.formCode
      var params
      if (this.formViewData && this.formViewData.saveCondition && this.formViewData.saveCondition.opt){          
            let temp = true
            let temp1 = this.saveConditionFunc(this.formViewData,this.JsondataFormat(val))
            temp = Boolean(!temp1)
            if (!temp) {
              params = { id: this.rowDataItem[this.formViewData.formKey], dataContent: this.JsondataFormat(val), formCode: formCode }
            } else {
              params = { formCode: formCode, formVersion: this.formVersion, dataContent: this.JsondataFormat(val) }
            }            
        } else {
          if (this.rowDataItem[this.formViewData.formKey]) {
            params = { id: this.rowDataItem[this.formViewData.formKey], dataContent: this.JsondataFormat(val), formCode: formCode }
          } else {
            params = { formCode: formCode, formVersion: this.formVersion, dataContent: this.JsondataFormat(val) }
          }
        }
        params.tenantCode = this.$store.state.user.tenantCode
        this.loading = true
        this.$interface.reports.addOrUpdateFormDataApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.loading = false
          this.$message.success(this.$t('success'))
          this.visible = false
          this.resetFormMaking()
          this.$emit('query')
        }).catch(() => {
          this.loading = false
        })
    },


    saveConditionFunc (item, row) {
      // !==
      if (item.saveCondition.opt === '!==') {
        if (row[item.saveCondition.column] !== item.saveCondition.value) {
          return true
        }
      }
      // ===
      if (item.saveCondition.opt === '===') {
        if (row[item.saveCondition.column] === item.saveCondition.value) {
          return true
        }
      }
      // in & List value
      if (item.saveCondition.opt === 'in' && Array.isArray(item.saveCondition.value)) {
        let temp = false
        for (let i = 0; i < item.saveCondition.value.length; i++) {
          const element = item.saveCondition.value[i]
          if (row[item.saveCondition.column] === element) {
            temp = true
            break
          }
        }
        return temp
      }
      // not null
      if (item.saveCondition.opt === 'notnull') {
        if (row && row[item.saveCondition.column]) {
          return true
        }
      }
    },
    apiRequest (data, row) {
      let params = {}
      params = this.execObject(data.params,row)

      let url = this.replaceString(data.url,row)
      this.loading = true
      this.$interface.customRequest(data.method, url, params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.loading = false
          return this.$message.error(res.msg)
        }
        this.loading = false
        this.resetFormMaking()
        this.visible = false
        this.$message.success(res.msg)
        this.$emit('query')
      }).catch((err) => {
        this.loading = false
      })
    },
    replaceString (str, row) {
      const reg = /\{(.*?)\}/g;
      if (reg.test(str)) {
        const regex = /\{(.*?)\}/;
        let field = str.match(regex);
        if (row) {
          if (!row[field[1]]) {
            this.$message.error(`${field[1]} field not found`)
            return str
          }
          str = str.replace(reg, row[field[1]])
        }
      }
      return str
    },
    replaceDataMapping (json1, json2) {
      for (var key in json2) {
        var value = json2[key];
        if (typeof json2[key] === "object") {
          json2[key] = this.replaceDataMapping(json1, json2[key])
        } else {
          while (typeof value === "string"&&value.indexOf("{") > -1) {
            var oldValue = value.substring(value.indexOf("{") + 1, value.indexOf("}"))
            var newValue = this.replaceString(json1[oldValue])
            if(typeof newValue === 'object'){
              value = newValue
            }else{
              value = value.replace("{" + oldValue + "}", newValue)
            }
          }
          json2[key] = value
        }
      }
      return json2
    },
    execObject (objStr,rowData) {
      let obj = {}
      let templateObj = {
        now: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format(),
        now_date: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        now_time: moment.tz(moment().utc(), this.$store.state.user.timezoneId).format('HH:mm:ss'),
        current_user_id: this.$store.state.user.id,
        current_user_name: this.$store.state.user.realName,
        now_utc: moment().utc().format(),
        now_date_utc: moment().utc().format('YYYY-MM-DD'),
        now_time_utc: moment().utc().format('HH:mm:ss')
      }
      obj = this.replaceDataMapping(Object.assign(templateObj, rowData), objStr)
      return obj
    },
  }
}
</script>
<style lang="scss">
@import "@/assets/scss/global.scss";
.toolong .el-form-item__content {
  overflow: scroll !important;
}
.submittUrl p {
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  a {
    color: $--theme-color;
  }
}

#form-view-css {
  .el-dialog {
    max-height: 95vh !important;
  }
  .el-dialog__body {
    max-height: 80vh;
    min-height: 20vh;
    padding: 20px !important;
    overflow-y: scroll !important;
  }
  .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /*height:600px;*/
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
  }
  .el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
  }
}
.fm-form {
  .fm-form-item > label {
    font-size: 50px;
  }
}
</style>
